package com.boat.sample.ddd.domain.system.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.boat.framework.base.exception.ServiceException;
import com.boat.framework.common.event.EventPub;
import com.boat.sample.ddd.api.errorcode.DddErrCode;
import com.boat.sample.ddd.domain.system.entity.LoginLog;
import com.boat.sample.ddd.domain.system.entity.User;
import com.boat.sample.ddd.domain.system.event.UserRegistered;
import com.boat.sample.ddd.domain.system.repository.LoginLogRepository;
import com.boat.sample.ddd.domain.system.repository.UserRepository;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class UserService {
	@Autowired
	UserRepository userRepository;
	@Autowired
	LoginLogRepository loginLogRepository;

	public User register(User user) {
		User example = new User();
		example.setUserName(user.getUserName());
		User userInfo = userRepository.getByExample(example);
		if (userInfo != null) {
			throw new ServiceException(DddErrCode.USER_ALREADY_EXISTS, new String[] { user.getUserName() });
		}
		user.setUserType("00");
		
		//user.register();
		userRepository.insert(user);
		
		EventPub.instance().post(new UserRegistered(user));
		
		return user;
	}
	
	public void createUserLog(String userName, String message) {
		LoginLog loginLog = new LoginLog();
		loginLog.setUserName(userName);
		loginLog.setMessage(message);
		loginLogRepository.insert(loginLog);
	}
}
